package utils;

import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

//@Slf4j
public class DateUtils {

    public static final String ONLY_DATE = "yyyy-MM-dd";
    public static final String DATE_TIME = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_TIME_NO_SENCOND = "yyyy-MM-dd HH:mm";
    public static final String DATE_TIME_FILE_NAME = "yyyyMMddHHmmss";
    public static final String DATE_CHINESE = "yyyy年MM月dd日";
    public static final String DATE_FORMAT = "yyyyMMdd";

    public static String getCurrent() {
        return getCurrent(DATE_TIME);
    }

    public static String getCurrent(String template) {
        Date date = new Date();
        return format(date, template);

    }

    public static String format(Date date, String template) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(template);
        return simpleDateFormat.format(date);
    }

    /**
     * Java将Unix时间戳转换成指定格式日期字符串
     * @param timestampString 时间戳 如："1473048265";
     * @param formats 要格式化的格式 默认："yyyy-MM-dd HH:mm:ss";
     *
     * @return 返回结果 如："2016-09-05 16:06:42";
     */
    public static String timestampToDate(String timestampString, String formats) {
        if (StringUtils.isEmpty(formats)) {
            formats = "yyyy-MM-dd HH:mm:ss";
        }

        if (StringUtils.isEmpty(timestampString)) {
//            log.error("null timestampString ...");
            return "";
        }

        if (timestampString.length() > 10 ) {
            timestampString = StringUtils.substring(timestampString, 0, 10);
        }

        Long timestamp = Long.parseLong(timestampString) * 1000;
        String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp));
        return date;
    }

    public static void main(String[] args) {
        String date = timestampToDate("1525596108122");
        System.out.println(date);
    }

    public static String timestampToDate(String timestampString) {
        return timestampToDate(timestampString, DATE_TIME_NO_SENCOND);
    }


    /**
     * 日期格式字符串转换成时间戳
     *
     * @param dateStr 字符串日期
     * @param format   如：yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String date2TimeStamp(String dateStr, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return String.valueOf(sdf.parse(dateStr).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
